import 'package:flutter/material.dart';
import 'global_context.dart';

class LoadingModule {
  static final LoadingModule _instance = LoadingModule._internal();
  factory LoadingModule() => _instance;
  LoadingModule._internal();

  OverlayEntry? _overlayEntry;

  bool get isShowing => _overlayEntry != null;

  void show() {
    if (isShowing) return; // 已显示，避免重复叠加

    _overlayEntry = OverlayEntry(
      builder: (context) => const Stack(
        children: [
          // 半透明遮罩
          Opacity(
            opacity: 0.5,
            child: ModalBarrier(dismissible: false, color: Colors.black),
          ),
          Center(
            child: CircularProgressIndicator(),
          ),
        ],
      ),
    );
    Overlay.of(globalContext!).insert(_overlayEntry!);
  }

  void hide() {
    if (!isShowing) return;
    _overlayEntry!.remove();
    _overlayEntry = null;
  }
}

// 全局调用函数，方便使用
void showLoading() {
  LoadingModule().show();
}

void hideLoading() {
  LoadingModule().hide();
}
